/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package com.desire.homework;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 多线程计算123...添加+-号等于100
 */
public class _50_多线程计算123_9添加符号等于100 {
    AtomicBoolean flag = new AtomicBoolean(true);

    /**
     * 多线程计算式子
     *
     * @param args
     */
    public static void main(String[] args) {
        var t = new _50_多线程计算123_9添加符号等于100();
        for (int i = 0; i < 5; i++) {
            new Thread(t::op, "T" + i).start();
        }
    }

    void op() {
        System.out.printf("%s 启动计算中 %n", Thread.currentThread().getName());
        String[] o = new String[]{"", "+", "-"};
        Random rand = new Random();
        StringBuffer str = new StringBuffer("1");
        Pattern p = Pattern.compile("(\\d+|-\\d+)");
        while (flag.get()) {
            for (int i = 2; i < 10; i++) {
                str.append(String.format("%s%d", o[rand.nextInt(o.length)], i));
            }
            //123456789 = 100
            String s = str.toString();
            Matcher m = p.matcher(s);
            List<Integer> ln = new ArrayList<>();
            while (m.find()) {
                ln.add(Integer.parseInt(m.group()));
            }
            int sum = ln.stream().reduce(0, Integer::sum);
            if (sum == 100) {
                flag.set(false);
                System.out.printf("[%s]:%s = 100%n", Thread.currentThread().getName(), s);
                break;
            } else {
                str.delete(1, str.length());
            }
        }
        System.out.printf("%s 结束 %n", Thread.currentThread().getName());
    }
}


